package com.du.ichat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.DialogFragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.du.ichat.databinding.ActivitySettingBinding;
import com.du.ichat.dialog.AvatarSelectDialog;
import com.du.ichat.utils.AvatarUtils;
import com.du.ichat.utils.BaseActivity;
import com.du.ichat.utils.CheckSumBuilder;
import com.du.ichat.utils.SpUtils;
import com.du.ichat.utils.UserManager;
import com.du.ichat.utils.Utils;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.nos.NosService;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SettingActivity extends BaseActivity {
    private ActivitySettingBinding binding;
    private NimUserInfo userinfo;
    private LoginInfo loginInfo;
    private AvatarUtils avatarUtils;
    private AvatarSelectDialog avatarSelectDialog;
    private FullDialog dialog;
    private Bitmap bitmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this , R.layout.activity_setting);
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        userinfo = SpUtils.getObject(this , "userinfo");
        loginInfo = SpUtils.getObject(this , "logininfo");
        avatarSelectDialog = new AvatarSelectDialog();
        avatarUtils = new AvatarUtils(this);
        avatarSelectDialog.setAvatarDialogListener(new AvatarSelectDialog.AvatarSelectDialogInterface() {
            @Override
            public void selectPhoto() {
                avatarUtils.selectPhoto();
            }

            @Override
            public void takePhoto() {
                avatarUtils.cameraPic();
            }
        });

        initView();




    }

    private void initView() {

        GlideApp.with(this).load(userinfo.getAvatar()).placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar).into(binding.avatarIv);
        binding.tvAccid.setText(loginInfo.getAccount());
        binding.tvNickname.setText(userinfo.getName());
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        dialog = new FullDialog();
        binding.avatarLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateAvatar();
            }
        });
        binding.nickNameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(ChangeNicknameActivity.class);
            }
        });
        binding.accidLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        binding.qrLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(QRCardActivity.class);
            }
        });
        binding.moreLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(MoreUserinfoActivity.class);
            }
        });
        binding.addressLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        binding.logoutLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NIMClient.getService(AuthService.class).logout();
                SharedPreferences sp = SettingActivity.this.getSharedPreferences("DailSystem", 0);
                sp.edit().clear().commit();
                MainActivity.finishThis();
                finish();
                startActivity(LoginActivity.class);
            }
        });

    }

    private void updateAvatar() {
        avatarSelectDialog.show(getSupportFragmentManager() , "dialog");
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("tag" , "resultcode : " + resultCode);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case 0: //从相册图片后返回的uri
                    //启动裁剪
                    startActivityForResult(avatarUtils.CutForPhoto(data.getData()),3);
                    break;
                case 1: //相机返回的 uri
                    //启动裁剪
                    String path = getExternalCacheDir().getPath();
                    String name =  "output.png";
                    startActivityForResult(avatarUtils.CutForCamera(path,name),3);
                    break;
                case 3:
                    try {
                        dialog.show(getSupportFragmentManager() , "dialog");
                        //获取裁剪后的图片，并显示出来
                        bitmap = BitmapFactory.decodeStream(
                                getContentResolver().openInputStream(avatarUtils.getmCutUri()));
                        File file = new File(new URI(avatarUtils.getmCutUri().toString()));

                        if(!file.exists()){
                            Utils.copyDefaultAvatarFile(this);
                        }else{
                            File trueFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath(),
                                    CheckSumBuilder.getMD5(userinfo.getAccount()) + ".png ");
                            if(trueFile.exists()){
                                trueFile.delete();
                            }
                            file.renameTo(trueFile);
                            file.delete();
                            uploadAvatar(trueFile);
                        }



                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }




    @SuppressLint("ValidFragment")
    public static class FullDialog extends DialogFragment {
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            this.setCancelable(false);
            View view = inflater.inflate(R.layout.dialog_login_loading , null , false);
            TextView tv = view.findViewById(R.id.dialog_tv);
            tv.setText("正在更新...");
            return view;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        userinfo = SpUtils.getObject(this , "userinfo");
        loginInfo = SpUtils.getObject(this , "logininfo");
        if(binding != null){
            binding.tvNickname.setText(userinfo.getName());
        }
    }


    private void uploadAvatar(final File localFile){

        NIMClient.getService(NosService.class).upload(localFile , "image/png").setCallback(new RequestCallback<String>() {
            @Override
            public void onSuccess(String s) {
                Log.e("tag" , "settingActivity nosService success : " + s);
                updateUserAvatar(s , localFile);
            }

            @Override
            public void onFailed(int i) {
                Log.e("Tag" , "nosService faild : " + i);
//                fullDialog.dismiss();
            }

            @Override
            public void onException(Throwable throwable) {
//                fullDialog.dismiss();
            }
        });

    }

    private void updateUserAvatar(String avatarUrl , final File localFile){
        Map<UserInfoFieldEnum, Object> fields = new HashMap<>(1);
        fields.put(UserInfoFieldEnum.AVATAR, avatarUrl);
        NIMClient.getService(com.netease.nimlib.sdk.uinfo.UserService.class).updateUserInfo(fields).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                List<String> accounts = new ArrayList<>();
                accounts.add(UserManager.getUserinfo(SettingActivity.this).getAccount());
                NIMClient.getService(com.netease.nimlib.sdk.uinfo.UserService.class).fetchUserInfo(accounts).setCallback(new RequestCallback<List<NimUserInfo>>() {
                    @Override
                    public void onSuccess(List<NimUserInfo> nimUserInfos) {

                        if(nimUserInfos.size() >0 ){
                            SpUtils.putObject(SettingActivity.this ,"userinfo" , nimUserInfos.get(0));
                            toast("更新成功");
                            Log.e("Tag" , "localfile : " + localFile.getAbsolutePath());
                            Log.e("Tag" , "localfile exists : " + localFile.exists());

                            GlideApp.with(SettingActivity.this).load(nimUserInfos.get(0).getAvatar()).placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar).into(binding.avatarIv);
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onFailed(int i) {

                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                });
            }

            @Override
            public void onFailed(int i) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }


}
